<?php
/**
* * Model Class
* 
* @author Guillermo Landín
* @link 
* 
* 
*/ 

class Productsmodel extends Model {

    function __construct()
    {
        parent::Model();
        
        $this->CI =& get_instance(); 
    }   

    //returns the list of products, grouped in an array of categories
    public function get_all_products()
    {
		
        $this->db->select('products.id_Products AS id, Name_Products AS title, Introduction_Products AS text, Main_Image AS image, categories.id_Categories AS parent_id, Title_Categories AS parent_name, Active_Categories, Parent_Categories, Big_Image', FALSE)
                ->from('products')
                ->join('categories', 'products.id_Categories = categories.id_Categories', 'left')
                ->where('categories.id_Categories != ', '')
                ->where('Active_Products', 1)
                ->order_by('Title_Categories, products.Name_Products', 'ASC');  
                                                                          
        $query = $this->db->get();  
        return $query->result_array();
		
    }

    //receives a db result and returns a new array, with results grouped in arrays of categories    
    public function group_into_categories($result = array()) {
        
        $all_cats = $this->get_all_categories();

        $return = array();
        // loop through categories
        foreach($all_cats as &$item){
            $row = array();
            if(($item["Parent_Categories"] == NULL) && ($item["id"] !== ONE_OFF_CAT_ID)){
                $row = array(
                        "name" => $item["title"],
                        "params" => $item["id"]);
                // loop through categories again, look for children categories
                $has_children = false;
                foreach($all_cats as &$subitem){
                    if($subitem["Parent_Categories"] == $item["id"]){
                        $has_children = true; // found it, loop through products, add items to subcategory and remove from $result
                        foreach($result as &$product){
                            if($product["parent_id"] == $subitem["id"]){
                                $row["items"][] = $product;
                                unset($product);
                            }
                        }
                        unset($subitem);
                    }
                }
                if ($has_children == false){
                    // didn't find any products in subcategories, loop through products, add items to category and remove from $result
                    foreach($result as &$product){
                        if($product["parent_id"] == $item["id"]){
                            $row["items"][] = $product;
                            unset($product);
                        }
                    }
                }
                unset($item);
            }
            if((!empty($row)) && (isset($row["items"]))) $return[] = $row;
        }

        return $return;
    }

    //return a list of all active categories with image, title and description. Categories with no products or subcats are returned too.
    public function get_all_categories()
    {
        $this->db->select('categories.id_Categories As id, Title_Categories As title, Description_Categories AS text, Image_Categories AS image, Parent_Categories, count(id_Products) AS product_count', FALSE)
                ->from('categories')
                ->join('products','categories.id_Categories = products.id_Categories','left')
                ->where('Active_Categories', 1)   
                ->group_by('categories.id_Categories')  
                ->order_by('Title_Categories', 'ASC');  

        $query = $this->db->get();
                                 
        return $query->result_array();
    }
    // return all top level categories that are active and are not subcategories and have active products as children or subcats that have them
    public function get_top_level_categories($fields='categories.id_Categories AS id, Title_Categories As title, Introduction_Categories AS text, Image_Categories AS image')
    {
        $this->db->select($fields. ", categories.id_Categories AS temp_id", FALSE)
                ->from('categories')                                                 
                ->join('products', 'products.id_Categories=categories.id_Categories', 'left')                                                 
                ->where('parent_Categories', NULL)                                   
                ->where('categories.id_Categories !=', ONE_OFF_CAT_ID)                                      
                ->group_by('categories.id_Categories')
                ->order_by('Title_Categories', 'ASC');  

        $query = $this->db->get();
        $result = $query->result_array();
        
        foreach($result as $key=>&$cat){  
            $subcats = $this->get_categories_by_parent($cat['temp_id']);
            if (empty($subcats)) $products = $this->get_products_by_category($cat['temp_id']);
            unset($cat['temp_id']);
            if (empty($subcats) && empty($products)) unset($result[$key]);         
        }

        return $result;
    }
    //return a list of all parent categories that have subcategories as direct children and no products
    public function get_all_parent_categories()
    {
        $this->db->select('categories.id_Categories As id, Title_Categories As title, Description_Categories AS text, Image_Categories AS image')
                ->from('categories')                                                 
                ->join('products', 'products.id_Categories=categories.id_Categories', 'left')                                                 
                ->where('parent_Categories', NULL)                                      
                ->where('Active_Categories', 1)                                      
                ->where('categories.id_Categories !=', ONE_OFF_CAT_ID)                                      
                ->having('count(id_Products)', 0) 
                ->group_by('categories.id_Categories')
                ->order_by('Title_Categories', 'ASC');  

        $query = $this->db->get();
        return $query->result_array();
    }

    //return a list of all active applications that have products with image, title and description
    public function get_all_parent_applications()
    {
        $this->db->select('applications.id_Applications AS id, Name_Applications As title, Image_Applications AS image, count(products.id_Products) AS product_count', FALSE)
                ->from('applications')
                ->join('applications_products', 'applications.id_Applications = applications_products.id_Applications', 'left')
                ->join('products', 'applications_products.id_Products = products.id_Products', 'left')
                ->where('Active_Applications', 1)                                                     
                ->where('Active_Products', 1)                                                     
                ->group_by('applications.id_Applications')
                ->order_by('Name_Applications', 'ASC');  


        $query = $this->db->get();  
        return $query->result_array();
    }

    //returns the list of products for a given application
    public function get_products_by_application($id = FALSE, $fields='products.id_Products AS id, Name_Products AS title, Introduction_Products AS text, Main_Image AS image, Big_Image')
    {        
        $this->db->select($fields.', id_Categories AS parent_id', FALSE)
                ->from('products')
                ->join('applications_products', 'products.id_Products = applications_products.id_Products', 'left')
                ->where('applications_products.id_Applications', $id)
                ->where('Active_Products', 1)    
                ->order_by('id_Categories, products.Name_Products', 'ASC'); 

        $query = $this->db->get();                                     
        return $query->result_array();
    }
     
    //returns the list of categories for a given application
    public function get_categories_by_application($id = FALSE){
        $this->db->select('products.id_Products AS id, Name_Products AS title, Introduction_Products AS text, Main_Image AS image, categories.id_Categories AS parent_id, Title_Categories As parent_name, Big_Image', FALSE)
                ->from('applications_products')
                ->join('products', 'applications_products.id_Products = products.id_Products', 'left') 
                ->join('categories', 'products.id_Categories = categories.id_Categories', 'left')
                ->where('Active_Products', 1)
                ->order_by('Title_Categories, products.Name_Products', 'ASC');  

        if ($id !== false) $this->db->where('id_Applications', $id);

        $query = $this->db->get();

        $result = $query->result_array();

        $grouped_result = $this->group_into_categories($result);   

        return $grouped_result;

    }

    //returns the data of a given application
    public function get_application($id = FALSE, $fields="*")
    {
        $this->db->select($fields)
                ->from('applications')
                ->where('id_Applications', $id)
                ->where('Active_Applications', 1)
                ->limit(1);
                                                
        $query = $this->db->get();
        return $query->row_array();
    }
    //returns the data of a given category
    public function get_category($id = FALSE, $fields="categories.*, count(id_Products) AS product_count, count(categories.id_Categories) AS subcat_count")
    {
        $this->db->select($fields, FALSE)
                ->from('categories')                                                 
                ->join('products', 'products.id_Categories=categories.id_Categories', 'left')
                ->where('categories.id_Categories', $id)          
                ->where('Active_Categories', 1)                                      
                //->having('count(id_Products) >', 0) 
                ->group_by('categories.id_Categories');
                                                
        $query = $this->db->get();
        return $query->row_array();
    }

                                       
    public function get_products_by_category($id = FALSE, $fields = 'products.id_Products AS id, Name_Products AS title, Introduction_Products AS text, Main_Image AS image, id_Categories AS parent_id, Big_Image')
    {        
        $this->db->select($fields, FALSE)
                ->from('products')
                ->where('Active_Products', 1)
                ->where('id_Categories', $id)    
                ->order_by('id_Categories, Name_Products', 'ASC'); 

        $query = $this->db->get();                                     
        return $query->result_array();
    }            
    // returns subcategories that have active products
    public function get_categories_by_parent($id = FALSE, $fields = 'categories.id_Categories AS id, Title_Categories AS title, Introduction_Categories AS text, Image_Categories AS image, Parent_Categories AS parent_id')
    {        
        $this->db->select($fields.', sum(Active_Products) AS active_product_counter', FALSE)
                ->from('categories')
                ->join('products', 'categories.id_Categories = products.id_Categories')
                ->group_by('categories.id_Categories')
                ->where('Active_Categories', 1)
                ->where('Parent_Categories', $id)    
                ->order_by('Title_Categories', 'ASC'); 

        $query = $this->db->get();                                     
        $result = $query->result_array();

        // remove subcategories that don't have active products
        foreach($result as $key=>&$cat){  
            if (!$cat["active_product_counter"]>0) unset($result[$key]);         
        }
        return $result;
    }


    //returns the list of products for a given subcategory 
    public function get_products_by_subcategory($id = FALSE){

        $this->db->select('products.id_Products As id, Name_Products AS title, CONCAT(Introduction_Products, Description_Products) AS text, ImageURL_Images AS image, Big_Image', FALSE)
                ->from('products')
                ->join('products_Images', 'products.id_Products = products_Images.id_Products', 'left')
                ->join('images', 'products_Images.id_Images = images.id_Images', 'left')                                         
                ->where('isMainImage_Images', 1)
                ->where('Active_Products', 1)
                ->where('products.id_SubCategories', $id)  
                ->order_by('products.Name_Products', 'ASC');    

        $query = $this->db->get();

        $result = $query->result_array();
                           
        return $result;

    }

    //returns the data of a given product
    public function get_product($id = FALSE, $fields='*'){

        $this->db->select($fields)
                ->from('products')
                ->join('categories', 'products.id_Categories = categories.id_Categories', 'left')
                ->where('id_Products', $id)
				->where('Active_Products', 1);

        $query = $this->db->get();
        $result = $query->row_array();

        return $result;

    }     

    //returns the images of a given product as a simple string
    public function get_product_images($id = FALSE){

        $this->db->select("*")
                ->from('products_images')       
                ->where('id_Products', $id)
                ->order_by('Order', 'ASC');  
        
        $query = $this->db->get();
        $result = $query->result_array();
        
        foreach($result as &$row){
            $row = $row['Image'];
        }

        return $result;

    }

    //returns the applications of a given product
    public function get_product_applications($id = FALSE){

        $this->db->select('applications.id_Applications, Name_Applications')
                ->from('applications')
                ->join('applications_products', 'applications_products.id_Applications = applications.id_Applications', 'left')
                ->join('products', 'products.id_Products = applications_products.id_Products', 'left')
                ->where('products.id_Products', $id)
                ->where('Active_Applications', 1)
                ->order_by('Name_Applications', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }
     
    //returns the specifications of a given product
    public function get_product_specifications($id = FALSE){

        $this->db->select('specs.Name_Specs, specs_products.Value, units.name_Units')
                ->from('specs_products')
                ->join('specs', 'specs_products.id_Specs= specs.id_Specs', 'left')
                ->join('units', 'specs_products.id_Units = units.id_Units', 'left')
                ->where('specs_products.id_Products', $id)
                ->where('Active_Specs', 1) 
                ->order_by('specs.Name_Specs', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;
		
    }

    //receives a result array and returns a string of Name_Finishes
    public function finishes_result_into_string($data = array()){

        $simple_array = array();
        foreach($data as $finish){
            $simple_array[] = $finish["Name_Finishes"];
        }

        return join(", ", $simple_array);

    }

    //returns the fnishes of a given product
    public function get_product_finishes($id = FALSE){

        $this->db->select('Name_Finishes')
                ->from('finishes_products')
                ->join('finishes', 'finishes_products.id_Finishes = finishes.id_Finishes', 'left')
                ->where('finishes_products.id_Products', $id)
                ->where('Active_Finishes', 1)
                ->order_by('Name_Finishes', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }

    //returns the list of products for $searchword
    public function get_prod_search_results($searchword){

         $this->db->select('products.id_Products AS id, Name_Products AS title, CONCAT(Introduction_Products, Description_Products) AS text, Main_Image AS image', FALSE)
                ->from('products')   
                ->join('categories', 'products.id_Categories = categories.id_Categories', 'left')
                ->where('Active_Products', 1)    
                ->where('Active_Categories', 1)    
                ->where('MATCH (Name_Products, Introduction_Products, Description_Products) AGAINST ("'.$searchword.'")', NULL, FALSE);

        $query = $this->db->get();    

        if ($query != NULL) {
            return $query->result_array();
        } else {
            return FALSE;
        }

    }        
    //returns the list of categories for $searchword
    public function get_cat_search_results($searchword){

         $this->db->select('categories.id_Categories AS id, Title_Categories AS title, CONCAT(Introduction_Categories, Description_Categories) AS text, Image_Categories AS image, sum(Active_Products) AS active_product_counter', FALSE)
                ->from('categories')   
                ->join('products', 'categories.id_Categories = products.id_Categories', 'left')   
                ->where('Active_Categories', 1)    
                ->where('MATCH (Title_Categories, Introduction_Categories, Description_Categories) AGAINST ("'.$searchword.'")', NULL, FALSE)
                ->group_by('categories.id_Categories');

        $query = $this->db->get();                                     

        if ($query != NULL) {
            $result = $query->result_array();
            // remove subcategories that don't have active products
            foreach($result as $key=>&$cat){  
                if (!$cat["active_product_counter"]>0) unset($result[$key]);         
            }
            return $result;
        } else {
            return FALSE;
        }

    }        
     
    // receives a simple array of product ids and returns an associative array of ids and names
    public function get_applications_data($ids = array())
    {
        if (empty($ids)) return $ids;
        $this->db->select("*")
                ->from('applications')  
                ->where_in('id_Applications', $ids)
                ->where('Active_Applications', 1); 
        
        $query = $this->db->get();
        return $query->result_array();
    }
    // receives a simple array of product ids and returns an associative array of ids and names
    public function get_finishes_data($ids = array())
    {
        if (empty($ids)) return $ids;
        $this->db->select("*")
                ->from('finishes')  
                ->where_in('id_Finishes', $ids)
                ->where('Active_Finishes', 1); 
        
        $query = $this->db->get();
        return $query->result_array();
    }                          
                                   
    public function get_spec_name($id = NULL)
    {
        $this->db->select("Name_Specs")
                ->from('specs')  
                ->where('id_Specs', $id)
                ->where('Active_Specs', 1); 
        
        $query = $this->db->get();
        $result = $query->row_array();

        return $result["Name_Specs"];
    }                              
    public function get_unit_name($id = NULL)
    {
        $this->db->select("name_Units")
                ->from('units')  
                ->where('id_Units', $id); 
        
        $query = $this->db->get();
        $result = $query->row_array();

        if (empty($result)) return FALSE;
        else return $result["name_Units"];

    }  
	
    //returns a list of products matching an array of ids
    public function get_products_by_id($ids=array(), $fields='id_Products, Name_Products, Introduction_Products, Main_Image')
    {        
		$string = "'".implode("','",$ids)."'";
        $this->db->select($fields." FROM products WHERE id_Products IN (".$string.") AND Active_Products=1 ORDER BY FIELD(id_Products, ".$string.")", FALSE);

        $query = $this->db->get();                                     
        return $query->result_array();
    }	

    // register product view by user (only if user hadn't viewed that product before)
    public function register_product_view($product_id = NULL, $user_id = NULL)
    {
        $this->db->select("*")
                ->from('products_users')                    
                ->where('id_Products', $product_id)
                ->where('id_Users', $user_id); 

        $query = $this->db->get();
        $result = $query->row_array();

        if(empty($result)){

            $row = array(
                'id_Products' => $product_id,
                'id_Users' => $user_id
            );
            $this->db->insert('products_users', $row);
        }
    }    
    
    // get list of products for "people who viewed this product also looked at:". Exclude products viewed by $user_id
    public function get_related_products($product_id = NULL, $user_id = NULL, $fields="products.id_Products AS id, Name_Products AS title, Introduction_Products AS text, Main_Image AS image, products.id_Categories AS parent_id, Big_Image")
    {
        // get list of users that have seen this product
        $this->db->select('id_Users')
                ->from('products_users')                    
                ->where('id_Products', $product_id)
                ->where('id_Users !=', $user_id); 

        $query = $this->db->get();
        $result = $query->result_array();
        $user_array = array();
        foreach($result as $row){
            $user_array[] = $row['id_Users'];
        }

        if (empty($user_array)) return array();

        // get most visited products by that list of users
        $this->db->select('products_users.id_Products, count(products_users.id_Products),'.$fields)
                ->from('products_users')   
                ->join('products', 'products_users.id_Products = products.id_Products', 'left')        
                ->join('categories', 'categories.id_Categories = products.id_Categories', 'left')        
                ->where_in('Active_Products', 1)
                ->where_in('Active_Categories', 1) 
                ->where_in('id_Users', $user_array)
                ->where('products.id_Products !=', $product_id)            
                ->group_by('products_users.id_Products')
                ->order_by('count(products_users.id_Products)', 'DESC')
                ->limit(6); 
        $query = $this->db->get();
        $result = $query->result_array();

        return $result;
    }    



/***********************************   
*   Smooth Gallery functions
***********************************/

public function get_big_img_all_products(){

    $this->db->select('Big_Image')
            ->from('products')           
            ->join('categories', 'products.id_Categories=categories.id_Categories', 'left')           
            ->where('Active_Products', 1)
            ->where('Active_Categories', 1);  
    
    $query = $this->db->get();
    return $query->result_array();

}
public function get_big_img_single_product($id=FALSE){

    $this->db->select('Big_Image')
            ->from('products')
            ->where('id_Products', $id)  
            ->where('Active_Products', 1);  
    
    $query = $this->db->get();
    return $query->result_array();

}                         
public function get_big_img_by_application($id=FALSE){

    $this->db->select('Big_Image')
            ->from('products')    
            ->join('applications_products', 'products.id_Products = applications_products.id_Products')    
            ->join('categories', 'products.id_Categories=categories.id_Categories', 'left')           
            ->where('applications_products.id_Applications', $id)  
            ->where('Active_Products', 1)
            ->where('Active_Categories', 1); 
    
    $query = $this->db->get();                  
    return $query->result_array();

}
public function get_big_img_by_category($id=FALSE){

    $subcats = $this->get_categories_by_parent($id, "categories.id_Categories AS id");

    if(!empty($subcats)) { //cat has subcats, get big image from active products inside those subcats

        $ids_string = "";
        foreach($subcats as $subcat){
            $ids_string .= $subcat["id"].",";
        }        

        $this->db->select('Big_Image')
                ->from('products')    
                ->where_in('products.id_Categories', rtrim($ids_string, ','))
                ->where('Active_Products', 1);  
    
        $query = $this->db->get();
        return $query->result_array();

    } else { //cat has products, get big images from those products

        $this->db->select('Big_Image')
                ->from('products')    
                ->where('products.id_Categories', $id)
                ->where('Active_Products', 1);  

        $query = $this->db->get();         
        return $query->result_array();
    }

}



/***********************************   
*   Sub-menu functions
***********************************/

    //returns an array of items under the given category. might be subcategories or products
    public function get_submenu_categories($id = FALSE, $prod_id = FALSE){

        $result = $this->get_top_level_categories("categories.id_Categories AS param, categories.Title_Categories AS name, sum(Active_Products) AS active_product_count"); 
                  
        //set the selected item and it's content
        foreach($result as $key=>&$item){

            $item['controller'] = 'products/categories/'.$item['param'];

            if ($item['param'] == $id) { 

                $subcats = $this->get_categories_by_parent($item['param']);
                                
                if (!empty($subcats)) { // if there are subcategories, show them

                    $cat_info = $this->get_category($id);
                    //$parent_name = url_title($cat_info['name'], '_', TRUE);

                    foreach($subcats as &$subitem){
                        $subitem = array( 
                                        'name' => $subitem['title'], 
                                        'controller' => 'products/categories/'.$subitem['id'], 
                                        'param' => $subitem['id']
                                        );
                    }
                    $item['content'] = $subcats;   

                } else { // else, show the products

                    $products = $this->get_products_by_category($item['param']); 

                    foreach($products as &$subitem){
                        $subitem = array( 
                                        'name' => $subitem['title'], 
                                        'controller' => 'products/view/'.$subitem['id'], 
                                        'param' => $subitem['id']
                                        );
                        if (($prod_id != FALSE) && ($subitem['param'] == $prod_id)) $subitem['selected'] = TRUE;
                    }
                    $item['content'] = $products;
                }
                $item['selected'] = TRUE;
            }
        }

        return $result;

    }

    //returns the products submenu for given subcategory
    public function get_submenu_subcategories($id = FALSE, $prod_id = FALSE){

        $cat_info = $this->get_category($id);
        $parent_id = $cat_info["Parent_Categories"];
        $parent_info = $this->get_category($parent_id);

        $result = $this->get_submenu_categories($parent_id); 
                                           
        //set the selected item and it's content
        foreach($result as &$item){
         
            if ($item['param'] == $parent_id) { 

                foreach($item['content'] as &$subitem){

                    if ($subitem['param'] == $id) { 
                        
                        $products = $this->get_products_by_category($id);
                        //$products = $this->get_products_by_subcategory($id); 

                        foreach($products as &$product){
                            $product = array( 
                                            'name' => $product['title'], 
                                            'controller' => 'products/view/'.$product['id'], 
                                            'param' => $product['id']
                                            );
                            if (($prod_id != FALSE) && ($product['param'] == $prod_id)) $product['selected'] = TRUE;

                        } 

                        $subitem['selected'] = TRUE;
                        $subitem['content'] = $products;
                    }

                }
            }
        }   
        //print "<pre>";print_r($result);print "</pre>";die();                                
        return $result;

    } 

    //returns an array of applications with fields 'name', 'controller' and 'param'
    public function get_submenu_applications($id = FALSE){
        
        $result = $this->get_all_parent_applications();

        foreach($result as &$row){
            $row = array( 
                            'name' => $row['title'], 
                            'controller' => 'products/applications/'.$row['id'], 
                            'param' => $row['id']
                            );
        }

        //set the selected item
        foreach($result as &$item){
            if ( $item['param'] == $id) $item['selected'] = TRUE;
        }
                       
        return $result;    

    }

    //returns an array of one-off-products with fields 'name', 'controller' and 'param'
    public function get_submenu_one_off($id = FALSE){

        $result = $this->get_products_by_category(ONE_OFF_CAT_ID);

        foreach($result as &$row){
            $row = array( 
                            'name' => $row['title'], 
                            'controller' => 'products/view/'.$row['id'], 
                            'param' => $row['id']
                            );
        }
        //set the selected item
        foreach($result as &$item){
            if ( $item['param'] == $id) $item['selected'] = TRUE;
        }

        return $result;

    }




##############################################
#   Manage session vars for search history
##############################################

    public function add_to_history($search_string = ''){

        $search_history = $this->session->userdata('prod_search_history');

        if ($search_history === FALSE) { // if session var doesn't exist

            $search_history = array($search_string); // create the array

        } else { // if session var already exists

            // check if search_string already exists in history
            if (in_array($search_string, $search_history)) {
                $key = array_search($search_string, $search_history); 
                unset($search_history[$key]); //remove keyword from array
                array_values($search_history); //re-index array
            }
            array_unshift($search_history, $search_string); //add keyword to beggining of array

        }

        $this->session->set_userdata('prod_search_history', $search_history); //finally, put vars in session array

    }

    public function get_search_string(){

        $search_string = $this->session->userdata('prod_search_history'); 

        if ($search_string === FALSE) return FALSE;

        else return $search_string[0];
    
    }               

    public function get_search_history(){

        $search_string = $this->session->userdata('prod_search_history'); 

        if ($search_string === FALSE) return FALSE;

        else return $search_string;
    
    }

    public function clear_search_history(){

        $this->session->unset_userdata('prod_search_history');
    
    }

    public function get_search_history_by_id($id = FALSE){

        $history = $this->session->userdata('prod_search_history');

        if (isset($history[$id])) return $history[$id];  
        else return FALSE;
    
    }


##############################################
# Admin methods
##############################################

    public function admin_get_all($fields='*'){

        $this->db->select($fields)
                ->from('products')
                ->order_by('Name_Products');  
        
        $query = $this->db->get();
        return $query->result_array();

    }                           
    public function admin_get_product($id=FALSE, $fields='*'){

        $this->db->select($fields)
                ->from('products')       
                ->where('id_Products', $id);  
        
        $query = $this->db->get();
        return $query->row_array();

    }              
    public function admin_get_all_categories($fields="*")
    {
        $this->db->select($fields)
                ->from('categories')
                ->order_by('Title_Categories', 'ASC');  

        $query = $this->db->get();
                                 
        return $query->result_array();
    }             
    //returns an associative array in json format for the admin select menu
    public function admin_get_json_categories()
    {
        $this->db->select('*')
                ->from('categories')
                ->order_by('Title_Categories', 'ASC');  

        $query = $this->db->get();
        $result = $query->result_array();

        $return = array();
        foreach($result as &$item){
            $row = array();
            if($item["Parent_Categories"] == NULL){
                $row["id"] = $item["id_Categories"];
                $row["title"] = $item["Title_Categories"];
            }
            
            foreach($result as &$subitem){
                if($subitem["Parent_Categories"] == $item["id_Categories"]){
                    $row["children"][] = array(
                                    "id" => $subitem["id_Categories"],
                                    "title" => $subitem["Title_Categories"]
                                    );
                    unset($subitem);
                }
            }

            if(!empty($row)) $return[] = $row;

            unset($item);
        }                
        return  $return;
    }         
    // get cats where parent is null and that have no products. Exclude one_off category and $id if given.
    public function admin_get_parent_categories($id=FALSE)
    {
        $this->db->select('categories.*')
                ->from('categories')                                                 
                ->join('products', 'products.id_Categories=categories.id_Categories', 'left') 
                ->where('parent_Categories', NULL)                                      
                ->where('categories.id_Categories !=', ONE_OFF_CAT_ID)                                      
                ->having('count(id_Products)', 0) 
                ->group_by('categories.id_Categories')
                ->order_by('Title_Categories', 'ASC');  
                                                        
        if ($id!==FALSE) $this->db->where('categories.id_Categories !=', $id);

        $query = $this->db->get();
        return $query->result_array();
    }
    //returns all the subcategories in given category or false if none exist
    public function admin_get_cat_children($id=FALSE, $fields="*")
    {
        $this->db->select($fields, FALSE)
                ->from('categories')                                                 
                ->where('parent_Categories', $id);  

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;
    }
    //returns all the products in given category
    public function admin_get_products_by_cat($id = FALSE, $fields="*")
    {        
        $this->db->select($fields, FALSE)
                ->from('products')
                ->where('id_Categories', $id)    
                ->order_by('id_Categories, products.Name_Products', 'ASC'); 

        $query = $this->db->get();                                     
        return $query->result_array();
    }   
    public function admin_get_category($id=NULL, $fields="*")
    {
        $this->db->select($fields)
                ->from('categories')     
                ->where('id_Categories', $id);  

        $query = $this->db->get();
        return $query->row_array();
    }
    public function admin_update_category($id=FALSE, $data=array())
    {
        $this->db->where('id_Categories', $id)
                ->update('categories', $data); 
    }   
    public function admin_insert_category($data=array()){

        $data["id_Categories"] = uniqid();
        $data["Active_Categories"] = 1;
        $this->db->insert('categories', $data); 
        return $data["id_Categories"];

    }     
    public function admin_delete_category($id=FALSE){

        $this->db->where('id_Categories', $id);
        $this->db->delete('categories'); 
                           
    }           
               
    public function admin_get_specification_products($id=FALSE, $fields='products.id_Products, products.Name_Products, products.Main_Image, products.Active_Products'){

        $this->db->select($fields)
                ->from('specs_products')   
                ->join('products', 'specs_products.id_Products = products.id_Products', 'left')       
                ->where('id_Specs', $id);  
        
        $query = $this->db->get();
        return $query->result_array();
    }        
    public function admin_get_application_products($id=FALSE, $fields='products.id_Products, products.Name_Products, products.Main_Image, products.Active_Products'){

        $this->db->select($fields)
                ->from('applications_products')   
                ->join('products', 'applications_products.id_Products = products.id_Products', 'left')       
                ->where('id_Applications', $id);  
        
        $query = $this->db->get();
        return $query->result_array();
    }        
    public function admin_get_finish_products($id=FALSE, $fields='products.id_Products, products.Name_Products, products.Main_Image, products.Active_Products'){

        $this->db->select($fields)
                ->from('finishes_products')   
                ->join('products', 'finishes_products.id_Products = products.id_Products', 'left')       
                ->where('id_Finishes', $id);  
        
        $query = $this->db->get();
        return $query->result_array();
    }        
             
    public function update_product($id=FALSE, $data=array()){

        $this->db->where('id_Products', $id)
                ->update('products', $data); 

    }   
    public function update_supplier($id=FALSE, $data=array()){

        $this->db->where('id_Supplier', $id)
                ->update('supplier', $data); 

    }   
    public function admin_update_finish($id=FALSE, $data=array()){

        $this->db->where('id_Finishes', $id)
                ->update('finishes', $data); 

    }   
    public function admin_update_application($id=FALSE, $data=array()){

        $this->db->where('id_Applications', $id)
                ->update('applications', $data);

    }      
    public function admin_insert_supplier($data=array()){

        $data["id_Supplier"] = uniqid();
        $this->db->insert('supplier', $data); 
        return $data["id_Supplier"];

    }          
    public function admin_delete_supplier($id=FALSE){

        $this->db->where('id_Supplier', $id);
        $this->db->delete('supplier'); 
                           
    }                             
    public function admin_delete_specification($id=FALSE){

        $this->db->where('id_Specs', $id);
        $this->db->delete('specs'); 

    }
    public function admin_delete_specification_products($id=FALSE){

        $this->db->where('id_Specs', $id);
        $this->db->delete('specs_products'); 

    }                             
    public function admin_delete_finish($id=FALSE){

        $this->db->where('id_Finishes', $id);
        $this->db->delete('finishes'); 

    }
    public function admin_delete_finish_products($id=FALSE){

        $this->db->where('id_Finishes', $id);
        $this->db->delete('finishes_products'); 

    }                             
    public function admin_delete_application($id=FALSE){

        $this->db->where('id_Applications', $id);
        $this->db->delete('applications'); 

    }
    public function admin_delete_application_products($id=FALSE){

        $this->db->where('id_Applications', $id);
        $this->db->delete('applications_products'); 

    }
    public function insert_product($data=array()){

        $data["id_Products"] = uniqid();
        $data["Active_Products"] = 0;
        $data["Approved_Products"] = 0;
        $this->db->insert('products', $data); 
        return $data["id_Products"];

    }   
    // delete product from all tables: from products, portfolios_products, wishlists_products, applications_products, finishes_products, images_products   
    public function admin_delete_product($id=FALSE){
        
        $tables = array(
                    'products', 
                    'portfolios_products', 
                    'wishlists_products', 
                    'applications_products', 
                    'finishes_products', 
                    'products_images',
                    'products_users');        

        $this->db->where('id_Products', $id);
        $this->db->delete($tables); 


    }  
    public function admin_insert_product_images($id=FALSE, $data=array()){

		 $len = count($data);
        for($i=0; $i<$len; $i++){

            $row = array(
                'id_Products' => $id,
                'Image' => $data[$i]
            );
            $this->db->insert('products_images', $row);

        }

    }
    public function admin_delete_product_images($id=FALSE){

        $this->db->where('id_Products', $id);
        $this->db->delete('products_images'); 

    }

    public function admin_get_product_specifications($id=FALSE, $fields="*"){

        $this->db->select($fields)
                ->from('specs_products')
                ->where('specs_products.id_Products', $id);

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }

    public function admin_get_all_specifications($fields="*"){

        $this->db->select($fields)
                ->from('specs')             
                ->order_by('Name_Specs', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }
    public function admin_delete_product_specifications($id=FALSE){

        $this->db->where('id_Products', $id);
        $this->db->delete('specs_products'); 

    } 
    public function admin_delete_product_applications($id=FALSE){

        $this->db->where('id_Products', $id);
        $this->db->delete('applications_products'); 

    }
    public function admin_delete_product_finishes($id=FALSE){

        $this->db->where('id_Products', $id);
        $this->db->delete('finishes_products'); 

    }
    public function admin_insert_product_specifications($id=FALSE, $data=array()){

        foreach($data as $spec){
            $spec['id_Products'] = $id;
            $this->db->insert('specs_products', $spec);
        }
    }                                                        
    public function admin_insert_product_applications($id=FALSE, $data=array()){

        foreach($data as $app){                                                                             
            $row = array(
                'id_Applications' => $app,
                'id_Products' => $id
            );
            $this->db->insert('applications_products', $row);
        }

    }
    public function admin_insert_product_finishes($id=FALSE, $data=array()){

        foreach($data as $finish){                                                                             
            $row = array(
                'id_Finishes' => $finish,
                'id_Products' => $id
            );
            $this->db->insert('finishes_products', $row);
        }

    }  

    public function admin_create_new_specification($name=FALSE){

        if ($name===FALSE) return FALSE;

        $row = array(
            'Name_Specs' => ucfirst($name),
            'Active_Specs' => 1
        );
        $this->db->insert('specs', $row);
        return $this->db->insert_id();

    }
    public function admin_get_all_units($fields="*"){

        $this->db->select($fields)
                ->from('units');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }
    public function admin_get_all_applications($fields="*"){

        $this->db->select($fields)
                ->from('applications')
                ->order_by('Name_Applications', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }
    public function admin_get_all_finishes($fields="*"){

        $this->db->select($fields)
                ->from('finishes')
                ->order_by('Name_Finishes', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }
    public function admin_get_all_suppliers($fields="*"){

        $this->db->select($fields)
                ->from('supplier')
                ->order_by('Name_Supplier', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }
    public function admin_get_supplier_info($id = FALSE, $fields="*"){

        $this->db->select($fields)
                ->from('supplier')
                ->where('id_Supplier', $id);

        $query = $this->db->get();
        $result = $query->row_array();

        return $result;

    }
    public function admin_get_supplier_products($id = FALSE, $fields="*"){

        $this->db->select($fields)
                ->from('products')
                ->where('id_Supplier', $id)
                ->order_by('Name_Products', 'ASC');

        $query = $this->db->get();
        $result = $query->result_array();

        return $result;

    }   
    public function admin_get_specification($id = FALSE, $fields="*"){

        $this->db->select($fields)
                ->from('specs')
                ->where('id_Specs', $id);

        $query = $this->db->get();
        $result = $query->row_array();

        return $result;

    }  
    public function admin_get_application($id = FALSE, $fields="*"){

        $this->db->select($fields)
                ->from('applications')
                ->where('id_Applications', $id);

        $query = $this->db->get();
        $result = $query->row_array();

        return $result;

    }  
    public function admin_get_finish($id = FALSE, $fields="*"){

        $this->db->select($fields)
                ->from('finishes')
                ->where('id_Finishes', $id);

        $query = $this->db->get();
        $result = $query->row_array();

        return $result;

    }  
    public function admin_update_specification($id=FALSE, $data=array()){

        $this->db->where('id_Specs', $id)
                ->update('specs', $data); 

    }   
    //returns the applications of a given product as a single array of ids
    public function admin_get_product_applications($id = FALSE){

        $this->db->select('id_Applications AS id')
                ->from('applications_products')
                ->where('id_Products', $id);

        $query = $this->db->get();
        $result = array();
        foreach ($query->result() as $row){
            $result[] = $row->id;
        }
        return $result;

    }
    //returns the finishes of a given product as a single array of ids
    public function admin_get_product_finishes($id = FALSE){

        $this->db->select('id_Finishes AS id')
                ->from('finishes_products')
                ->where('id_Products', $id);

        $query = $this->db->get();
        $result = array();
        foreach ($query->result() as $row){
            $result[] = $row->id;
        }
        return $result;

    } 
    public function admin_create_new_application($data=array()){

        $data["Active_Applications"] = 1;
        $this->db->insert('applications', $data); 
        return $this->db->insert_id();

    }
    public function admin_create_new_finish($name=FALSE){

        if ($name===FALSE) return FALSE;
        $row = array(
            'Name_Finishes' => ucfirst($name),
            'Active_Finishes' => 1
        );
        $this->db->insert('finishes', $row);
        return $this->db->insert_id();

    }


    /**
    * Is duplicated value?
    * 
    * @access public
    * @param string $field - Field to be searched
    * @param string $value 
    * @return boolean - true is it is a duplicated value
    */    
    public function is_duplicated($table, $field, $value, $exc_field=FALSE, $exc_id=FALSE)
    {
    
        $this->db->select('count(1) as counter')
                ->from($table)
                ->where($field, $value);        
        if(($exc_field!==FALSE) && (($exc_id!==FALSE))) $this->db->where($exc_field.' !=', $exc_id);


        $query = $this->db->get();
        $row = $query->row_array();
        if($row == NULL)
            return FALSE;
        
        if($row["counter"] > 0){
            return TRUE;
        }else{
            return FALSE;
        }

    } 


}
